package com.bancomer.batch.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.bancomer.batch.Constants;
import com.bancomer.batch.pojo.Alert;

public class StringConverter {
	public static String convertPatternToDate(String text) throws Exception{
		String result = "";
		StringBuffer buffer = new StringBuffer(text);
		StringBuffer bufferResult = new StringBuffer();
		String pattern="";
		SimpleDateFormat format = null;
		String date = "";
		for(int i=0; i<buffer.length(); i++){
			if(buffer.charAt(i)=='$'){
				if(buffer.charAt(i+1)=='{'){
					int position = buffer.indexOf("}",i);
					if(Constants.formatDate==null||"".equals(Constants.formatDate)){
						pattern = buffer.substring(i+2,position);
						Constants.formatDate = pattern; 
					}
					else{
						pattern = Constants.formatDate;
					}
					try{
						format = new SimpleDateFormat(pattern);
						if(Constants.alertDate==null||"".equals(Constants.alertDate)){
							date = format.format(new Date());
						}
						else{
							date = format.format(format.parse(Constants.alertDate));
						}
					    bufferResult.append(date);
					    i=position;
						}
					catch(ParseException e){
						format = new SimpleDateFormat("yyMMdd");
						date = format.format(new Date());
					}
				}
			}
			else{
				bufferResult.append(buffer.charAt(i));
			}
		}
		result = bufferResult.toString();
		return result;
	}
	/*public static void main (String [] args) throws Exception{
		Constants.alertDate = "140728";
		//Constants.formatDate = "ddMMyyyy";
		//String fileName = "TABLA008.BIGDATA.D1${yyMMdd}.txt";
		String fileName = "${yyMMdd}";
		System.out.println("Original "+fileName);
		System.out.println("Formateado "+convertPatternToDate(fileName));
	}*/
}
